package com.study.controller;


import com.study.bean.entity.DormitoryBuilding;
import com.study.bean.entity.StuCounter;
import com.study.bean.entity.Student;
import com.study.bean.query.BuildAdmin;
import com.study.bean.query.Rooms;
import com.study.bean.query.StudentQuery;
import com.study.bean.vo.StudentVO;
import com.study.service.impl.StudentServiceImpl;
import com.study.util.MyBeanUtils;
import com.study.util.PageInfo;
import com.study.util.Result;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet("/student/*")
public class StudentController extends BaseController {
    private final StudentServiceImpl studentService = new StudentServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");

        switch (method){
            case "selectByPage":
                selectByPage(req, resp);
                break;
            case "delById":
                delById(req, resp);
                break;
            case "selectbuild":
                selectbuild(req,resp);
                break;
            case "selectRoom":
                selectRoom(req,resp);
                break;
            case "selectById":
                seletById(req,resp);
                break;
            case "addStudent":
                addStudent(req,resp);
                break;
            case "updateStudent":
                updateStudent(req,resp);
                break;
            case "login":
                login(req,resp);
                break;
        }
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {

        String sno = req.getParameter("sno");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        String regexName = "^[a-zA-Z0-9_\\u4e00-\\u9fa5\\s·]+$";
        Pattern pattern = Pattern.compile(regexName);
        Matcher matcher = pattern.matcher(sno);
        if (!matcher.find()) {
            toJSON(resp, Result.error("用户名不能有特殊字符"));
            return;
        }

        //先判断验证码是不是正确
        //1、验证码错误，返回一个验证码错误的提示
        //2、验证码正确，再验证验证码是不是正确
        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)) {
            toJSON(resp, Result.error("验证码错误"));
            return;
        }

        StuCounter stu = studentService.login(sno, password);
        /*if (user == null) {
            JSONUtils.toJSON(resp, Result.error("用户名或者密码错误"));
        } else {
            if (user.getStatus() == 0) {
                JSONUtils.toJSON(resp, Result.error("该用户已经禁用，请联系管理员"));
                return;
            }
            session.setAttribute("user", user);
            JSONUtils.toJSON(resp, Result.ok("登录成功"));

        }*/
        if (stu == null) {
            toJSON(resp, Result.error("用户名或者密码错误"));
            return;
        }

        //自动登录
        //判断有没有勾选自动登录
        String autoLogin = req.getParameter("autoLogin");
        if (!ObjectUtils.isEmpty(autoLogin)) {
            Cookie cookie = new Cookie("autoLogin", stu.getSno() + "&" + stu.getPassword());
            //设置Cookie 的存活时间和绑定路径
            cookie.setMaxAge(60 * 60 * 24 * 7);//设置时间为1周
            cookie.setPath(req.getContextPath());
            //在响应resp中添加cookie，返回给浏览器
            resp.addCookie(cookie);
        }

        session.setAttribute("stu", stu);
        toJSON(resp, Result.ok("登录成功"));

    }

    private void updateStudent(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("StudentController.updateStudent");
        Student student = MyBeanUtils.copyToBean(req, Student.class);
        System.out.println(student);
        Boolean b = studentService.updateStudent(student);
        if (b){
            PageInfo pageInfo = new PageInfo(0, b);
            toJSON(resp, pageInfo);
        }else {
            PageInfo pageInfo = new PageInfo(1, b);
            toJSON(resp, pageInfo);
        }
    }

    private void addStudent(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("StudentController.addStudent");
        Student student = MyBeanUtils.copyToBean(req, Student.class);
        Boolean b = studentService.addStudent(student);
        if (b){
            PageInfo pageInfo = new PageInfo(0, b);
            toJSON(resp, pageInfo);
        }else {
            PageInfo pageInfo = new PageInfo(1, b);
            toJSON(resp, pageInfo);
        }
    }

    private void seletById(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("StudentController.seletById");
        String id = req.getParameter("id");
        System.out.println(id);
        StudentVO studentVO = studentService.selectById(Integer.parseInt(id));
        System.out.println(studentVO);
        PageInfo pageInfo = new PageInfo(0, studentVO);

        toJSON(resp, pageInfo);
    }

    private void selectRoom(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("StudentController.selectRoom");
        String buildId = req.getParameter("buildId");
        List<Rooms> rooms = studentService.selectRoom(Integer.parseInt(buildId));
        List<BuildAdmin> buildAdmins = studentService.selectAdmin(Integer.parseInt(buildId));
        List<List> lists = new ArrayList<>();
        lists.add(rooms);
        lists.add(buildAdmins);
        toJSON(resp, lists);
    }

    private void selectbuild(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("StudentController.selectbuild");
        List<DormitoryBuilding> buildings =  studentService.selectbuild();
        toJSON(resp, buildings);
    }



    private void delById(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("StudentController.delById");
        String id = req.getParameter("id");
        String status = req.getParameter("status");
        int rs= studentService.delById(Integer.parseInt(id),Integer.parseInt(status));
        if (rs ==1){
            toJSON(resp, Result.ok("删除成功"));
        }else {
            toJSON(resp, Result.ok("删除失败"));
        }
    }


    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("BlogServlet.selectByPage");
        /*String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String name = req.getParameter("name");
        BlogQuery blogQuery = new BlogQuery(Integer.parseInt(page), Integer.parseInt(limit), name);*/
        StudentQuery studentQuery = MyBeanUtils.copyToBean(req, StudentQuery.class);
        System.out.println(studentQuery);
        PageInfo pageInfo = studentService.selectByPage(studentQuery);

        //JSONUtils.toJSON(resp, pageInfo);
        toJSON(resp, pageInfo);
    }
}
